//TODO: When server starts up all game IDs that are searching
//need to be added to queue

//TODO: Limit the number of games a person can start

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.Runnable;
import java.lang.Thread;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.*;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;

public class ConnectionHandler implements Runnable{

	//Board Stuff
	private static final int BOARD_HEIGHT = 8;
	private static final int BOARD_WIDTH = 8;
	private static int numMines = 10;

	private static final char BOMB_SPACE = 'B';
	private static final char FLAGGED_SPACE = 'F';

	public static final int ELEMENTS_PER_GAME_PACKAGE = 4;



	private Socket socket;
	private static Queue<Integer> searchingPlayers;
	public ConnectionHandler(Socket socket){
		this.socket = socket;

		if(searchingPlayers == null)
			searchingPlayers = new LinkedList<Integer>();
		Thread t = new Thread(this);
		t.start();
	}

	public static void addSearchingGamesToQueue() {
		try {
			Class.forName("com.mysql.jdbc.Driver");
			Connection con = DriverManager.getConnection("jdbc:mysql://localhost/BDD?user=root");
			Statement st = con.createStatement();
			ResultSet rs;

			String sql = "SELECT user_id FROM users WHERE searching_for_game = 1";
			rs = st.executeQuery(sql);
			searchingPlayers = new LinkedList<Integer>();

			while(rs.next()) {
				int idToAdd = rs.getInt("user_id");
				searchingPlayers.add(idToAdd);
			}
			con.close();
			st.close();
			rs.close();

		}
		catch(Exception ex) {
			ex.printStackTrace();
		}
	}

	public void run() {
		try{

			//Gets a message from the phone
			ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
			String[] message = (String[])ois.readObject();
			System.out.println("action: " + message[0]);
			String[] response = new String[1];
			response[0] = "blank";


			if(message[0].equals("newUser")){

				//The phone is creating a new user								
				Class.forName("com.mysql.jdbc.Driver");
				Connection con = DriverManager.getConnection("jdbc:mysql://localhost/BDD?user=root");
				Statement st = con.createStatement();

				Statement st1 = con.createStatement();
				ResultSet playerCheck = st1.executeQuery("SELECT user_id FROM users WHERE name='" + message[1] +"'");

				if(getRowCount(playerCheck) != 0){
					//The user is already in the Database
					response[0] = "user_already_in_database";
				}
				else{   
					//Successfully added new user
					response[0] = "added";
					st.executeUpdate("INSERT users VALUES(null,'" + message[1] + "','"+ message[2] + "', 0, 0, 0, FALSE)");
				}
				st1.close();
				st.close();
				con.close();
			}
			else if(message[0].equals("login")){
				//TODO: Get rid of auto login and just store password in phone database
				System.out.println("In the login!");
				Class.forName("com.mysql.jdbc.Driver");
				Connection con = DriverManager.getConnection("jdbc:mysql://localhost/BDD?user=root");
				Statement st = con.createStatement();
				Statement st1 = con.createStatement();
				Statement st2 = con.createStatement();
				ResultSet rs;

				rs = st.executeQuery("SELECT * FROM Users WHERE name='" + message[1] + "'");
				rs.first();
				System.out.println("The password: " + rs.getString("password"));
				if(getRowCount(rs) == 0){
					if(message[2].equals("auto_login")){
						response[0] = "account_does_not_exist_auto_login";
					}
					else{
						response[0] = "account_does_not_exist";
					}										
				}
				else if(!(rs.getString("password").equals(message[2])||message[2].equals("auto_login") )){
					response[0] = "incorrect_password";
				}
				else{
					int userID = rs.getInt("user_id");
					ResultSet hostPlayer, awayPlayer;
					hostPlayer = st1.executeQuery("SELECT u.name, u.user_id, g.host_players_turn, g.idActive_Games, g.need_game_ok FROM users u, active_games g WHERE g.host_player="+userID+" and u.user_id=g.away_player");
					awayPlayer = st2.executeQuery("SELECT u.name, u.user_id, g.host_players_turn, g.idActive_Games, g.need_game_ok FROM users u, active_games g WHERE g.away_player="+userID+" and u.user_id=g.host_player");


					response = new String[2 + (getRowCount(hostPlayer) + getRowCount(awayPlayer))*ELEMENTS_PER_GAME_PACKAGE];

					if(searchingPlayers.contains(userID)){
						response[response.length - 1] = "is_searching";
					}
					else{
						response[response.length - 1] = "not_searching";
					}

					if(message[2].equals("auto_login")){
						response[0] = "auto_success";
					}
					else{
						response[0] = "success";
					}

					addGameData(response, hostPlayer, awayPlayer);

					hostPlayer.close();
					awayPlayer.close();
				}

				rs.close();
				st.close();
				st1.close();
				st2.close();
				con.close();
			}
			else if(message[0].equals("fetch_games")){
				Class.forName("com.mysql.jdbc.Driver");
				Connection con = DriverManager.getConnection("jdbc:mysql://localhost/BDD?user=root");
				Statement st = con.createStatement();
				Statement st1 = con.createStatement();
				Statement st2 = con.createStatement();
				ResultSet rs;

				String username = message[1];

				rs = st.executeQuery("SELECT user_id FROM Users WHERE name='" + username + "'");
				rs.first();
				int userID = rs.getInt("user_id");

				if(getRowCount(rs) == 0) {
					response[0] = "ERROR";										
				}
				else {
					ResultSet hostPlayer, awayPlayer;
					hostPlayer = st1.executeQuery("SELECT u.name, u.user_id, g.host_players_turn, g.idActive_Games, g.need_game_ok FROM users u, active_games g WHERE g.host_player="+userID+" and u.user_id=g.away_player");
					awayPlayer = st2.executeQuery("SELECT u.name, u.user_id, g.host_players_turn, g.idActive_Games, g.need_game_ok FROM users u, active_games g WHERE g.away_player="+userID+" and u.user_id=g.host_player");


					response = new String[2 + (getRowCount(hostPlayer) + getRowCount(awayPlayer))*ELEMENTS_PER_GAME_PACKAGE];
					response[0] = "success";

					if(searchingPlayers.contains(userID)){
						response[response.length - 1] = "is_searching";
					}
					else{
						response[response.length - 1] = "not_searching";
					}

					addGameData(response, hostPlayer, awayPlayer);

					hostPlayer.close();
					awayPlayer.close();
				}
				rs.close();
				st.close();
				st1.close();
				st2.close();
				con.close();
			}
			else if(message[0].equals("random_opponent")){
				Class.forName("com.mysql.jdbc.Driver");
				Connection con = DriverManager.getConnection("jdbc:mysql://localhost/BDD?user=root");
				Statement st = con.createStatement();
				Statement st1 = con.createStatement();
				Statement st2 = con.createStatement();
				Statement st3 = con.createStatement();
				Statement st4 = con.createStatement();
				ResultSet rs, rs1, rs2;

				rs = st.executeQuery("SELECT user_id FROM Users WHERE name='" + message[1] + "'");
				rs.first();

				int playerID = rs.getInt("user_id");

				synchronized(searchingPlayers){
					if(!searchingPlayers.contains(playerID)){
						searchingPlayers.add(playerID);
						System.out.println("Adding player: " + playerID);
						System.out.println("Length of queue: " + searchingPlayers.size());

						for (Integer i : searchingPlayers)
						{
							System.out.println("Player: " + i);
						}

						if(searchingPlayers.size() > 1){
							response = new String[5];
							response[1] = "new_game_created";
							//There are 2 players in waiting queue so create game
							int hostPlayer = searchingPlayers.remove();
							int awayPlayer = searchingPlayers.remove();

							System.out.println("Removing players: " + hostPlayer + " and " + awayPlayer);

							//Get Id of game last created?
							st1.executeUpdate("INSERT active_games VALUES(null, '" + createRandomBoard() + "', " + hostPlayer + ", "+ awayPlayer + ",TRUE , -1000, -1000, -1000, -1000, -1000, -1000, -1)");
							st2.executeUpdate("UPDATE Users SET searching_for_game = FALSE WHERE user_id=" + hostPlayer);

							rs1 = st3.executeQuery("SELECT LAST_INSERT_ID()");
							rs1.next();
							response[2] = Integer.toString(rs1.getInt(1));

							rs2 = st4.executeQuery("SELECT u.name FROM users u WHERE u.user_id = " + hostPlayer);

							rs2.next();
							response[3] = rs2.getString("name");


							response[4] = "their_turn";

							rs1.close();
							rs2.close();

						}
						else{
							//You are the only player in waiting queue
							st1.executeUpdate("UPDATE Users SET searching_for_game = TRUE WHERE name='" + message[1] + "'");
							response = new String[2];
							response[1] = "only_player";
						}
						response[0] = "started_search";
					}
					else{
						response[0] = "already_searching";
					}

				}


				rs.close();
				st4.close();
				st3.close();
				st2.close();
				st1.close();
				st.close();

			}
			else if(message[0].equals("input_opponent")){
				Class.forName("com.mysql.jdbc.Driver");
				Connection con = DriverManager.getConnection("jdbc:mysql://localhost/BDD?user=root");
				Statement st = con.createStatement();
				Statement st1 = con.createStatement();
				Statement st2 = con.createStatement();
				ResultSet rs, rs1, rs2;

				String hostPlayer = message[1];
				String awayPlayer = message[2];

				rs = st.executeQuery("SELECT user_id FROM Users WHERE name='" + hostPlayer + "'");
				rs.first();				
				int hostPlayerID = rs.getInt("user_id");

				rs1 = st1.executeQuery("SELECT user_id FROM Users WHERE name='" + awayPlayer + "'");
				rs1.first();				
				int awayPlayerID = rs1.getInt("user_id");

				response = new String[6];

				//outcome
				response[0] = "player_search_game_success";

				//game created?
				response[1] = "new_game_created";

				//Get Id of game last created?
				st2.executeUpdate("INSERT active_games VALUES(null, '" + createRandomBoard() + "', " + hostPlayerID + ", "+ awayPlayerID + ",TRUE , -1000, -1000, -1000, -1000, -1000, -1000, " + awayPlayerID + ")");


				rs2 = st2.executeQuery("SELECT LAST_INSERT_ID()");
				rs2.next();

				//ID of game
				response[2] = Integer.toString(rs2.getInt(1));

				//opponent
				response[3] = awayPlayer;

				//whose turn
				response[4] = "your_turn";
				
				response[5] = "0";

				con.close();
				st.close();
				st1.close();
				rs.close();
				rs1.close();
				rs2.close();				
			}
			else if(message[0].equals("get_game")){
				response = new String[5];
				Class.forName("com.mysql.jdbc.Driver");
				Connection con = DriverManager.getConnection("jdbc:mysql://localhost/BDD?user=root");
				Statement st = con.createStatement();
				Statement st2 = con.createStatement();
				Statement st3 = con.createStatement();
				Statement st4 = con.createStatement();
				ResultSet rs, rs1, rs2;

				rs = st.executeQuery("SELECT * FROM active_games g WHERE g.idactive_Games = " + message[1]);
				response[4] = message[1];

				if(rs.next()){
										
					response[0] = "game_retrieved";
					response[1] = rs.getString("game_board");

					if(rs.getInt("host_players_turn") == 1){
						rs1 = st2.executeQuery("SELECT u.name FROM users u, active_games g WHERE u.user_id = g.host_player");
						if(rs1.next()){
							response[2] = rs1.getString("name");
							response[3] = rs1.getString("name");
						}
						else{
							response[0] = "ERROR1";
						}
					}
					else{
						rs1 = st2.executeQuery("SELECT u.name FROM users u, active_games g WHERE u.user_id = g.away_player");
						rs2 = st3.executeQuery("SELECT u.name FROM users u, active_games g WHERE u.user_id = g.host_player");

						if(rs1.next()){
							response[2] = rs1.getString("name");
						}
						else{
							response[0] = "ERROR1";
						}

						if(rs2.next()){
							response[3] = rs2.getString("name");
						}
						else{
							response[0] = "ERROR1";
						}

						rs2.close();
					}
					rs1.close();					
				}
				else{
					response[0] = "ERROR2";
				}
				con.close();
				st.close();
				st2.close();
				st3.close();
				rs.close();

			}
			else if(message[0].equals("score_screen")){
				response = new String[11];
				int gameId = Integer.parseInt(message[1]);
				String shouldUpdate = message[2];
				Class.forName("com.mysql.jdbc.Driver");
				Connection con = DriverManager.getConnection("jdbc:mysql://localhost/BDD?user=root");
				Statement st = con.createStatement();
				Statement st1 = con.createStatement();
				Statement st2 = con.createStatement();
				Statement st3 = con.createStatement();
				ResultSet rs;
				ResultSet rs1;
				ResultSet rs2;

				response[0] = "success_score_screen";
				rs = st.executeQuery("SELECT * FROM active_games g WHERE g.idactive_games = " + gameId);
				if(rs.next()){
					if(rs.getInt("need_game_ok") >= 0 && shouldUpdate.equals("update")) {
						String updateSql = "UPDATE active_games SET need_game_ok=-1 WHERE idactive_games=" + message[1];
						st3.executeUpdate(updateSql);
					}
					String hostPlayer = rs.getString("host_player");
					String awayPlayer = rs.getString("away_player");
					int host_players_turn = rs.getInt("host_players_turn");
					int host_player_r1_score = rs.getInt("host_player_r1_score");
					int host_player_r2_score = rs.getInt("host_player_r2_score");
					int host_player_r3_score = rs.getInt("host_player_r3_score");
					int away_player_r1_score = rs.getInt("away_player_r1_score");
					int away_player_r2_score = rs.getInt("away_player_r2_score");
					int away_player_r3_score = rs.getInt("away_player_r3_score");

					rs1 = st1.executeQuery("SELECT u.name FROM users u WHERE u.user_id=" + hostPlayer);

					if(rs1.next()){
						hostPlayer = rs1.getString("name");
					}
					else{
						response[0] = "ERROR";
					}

					rs2 = st2.executeQuery("SELECT u.name FROM users u WHERE u.user_id=" + awayPlayer);

					if(rs2.next()){
						awayPlayer = rs2.getString("name");
					}
					else{
						response[0] = "ERROR";
					}

					response[1] = hostPlayer;
					response[2] = awayPlayer;
					response[3] = Integer.toString(host_players_turn);
					
					if(host_player_r1_score == -1000) {
						response[4] = "-";
					}
					else {
						response[4] = Integer.toString(host_player_r1_score);
					}
					if(away_player_r1_score == -1000){
						response[5] = "-";
					}
					else {
						response[5] = Integer.toString(away_player_r1_score);
					}
					if(host_player_r2_score == -1000){
						response[6] = "-";
					}
					else {
						response[6] = Integer.toString(host_player_r2_score);
					}
					if(away_player_r2_score == -1000){
						response[7] = "-";
					}
					else {
						response[7] = Integer.toString(away_player_r2_score);
					}
					if(host_player_r3_score == -1000){
						response[8] = "-";
					}
					else {
						response[8] = Integer.toString(host_player_r3_score);
					}
					if(away_player_r3_score == -1000){
						response[9] = "-";
					}
					else {
						response[9] = Integer.toString(away_player_r3_score);
					}
					response[10] = Integer.toString(gameId);

					rs1.close();
					rs2.close();
				}
				else{
					response = new String[1];
					response[0] = "ERROR";
				}
				con.close();
				st.close();
				st1.close();
				st2.close();
				rs.close();
			}
			else if(message[0].equals("deny_game")){
				System.out.print("in deny game!!!");
				String gameId = message[1];
				response = new String[1];
				response[0] = "success_deny_game";
				System.out.println("In deny Game");
				Class.forName("com.mysql.jdbc.Driver");
				Connection con = DriverManager.getConnection("jdbc:mysql://localhost/BDD?user=root");
				Statement st = con.createStatement();
				String sql = "UPDATE active_games SET need_game_ok=-2, host_players_turn=2 WHERE idactive_games=" + gameId;
				st.executeUpdate(sql);
				
				con.close();
				st.close();
			}
			else if(message[0].equals("turn_over")){
				response = new String[3];
				System.out.println("in turn over");
				Class.forName("com.mysql.jdbc.Driver");
				Connection con = DriverManager.getConnection("jdbc:mysql://localhost/BDD?user=root");
				Statement st = con.createStatement();
				Statement st1 = con.createStatement();
				Statement st2 = con.createStatement();
				Statement st3 = con.createStatement();
				ResultSet rs;
				int turnScore = Integer.parseInt(message[1]);
				int gameId = Integer.parseInt(message[2]);
				response[2] = message[1];
				rs = st1.executeQuery("SELECT * FROM active_games g WHERE g.idactive_games = " + gameId);

				if(rs.next()){
					response[0] = "board_updated";
					if(rs.getInt("host_player_r1_score") == -1000) {
						String sql = "UPDATE active_games SET host_players_turn=0, host_player_r1_score=" + turnScore + "  WHERE idactive_games=" + gameId;
						System.out.println(st.executeUpdate(sql));
						response[1] = "p1r1";
					}
					else if(rs.getInt("away_player_r1_score") == -1000) {
						String sql = "UPDATE active_games SET host_players_turn=1, away_player_r1_score=" + turnScore + ", game_board='" + createRandomBoard() + "'  WHERE idactive_Games = " + gameId;
						st.executeUpdate(sql);
						response[1] = "p2r1";
					}
					else if(rs.getInt("host_player_r2_score") == -1000) {
						String sql = "UPDATE active_games SET host_players_turn=0, host_player_r2_score=" + turnScore + "  WHERE idactive_Games = " + gameId;
						st.executeUpdate(sql);
						response[1] = "p1r2";
					}
					else if(rs.getInt("away_player_r2_score") == -1000) {
						String sql = "UPDATE active_games SET host_players_turn=1, away_player_r2_score=" + turnScore + ", game_board='" + createRandomBoard() + "'  WHERE idactive_Games = " + gameId;
						st.executeUpdate(sql);
						response[1] = "p2r2";
					}
					else if(rs.getInt("host_player_r3_score") == -1000) {
						String sql = "UPDATE active_games SET host_players_turn=0, host_player_r3_score=" + turnScore + "  WHERE idactive_Games = " + gameId;
						st.executeUpdate(sql);
						response[1] = "p1r3";
					}
					else if(rs.getInt("away_player_r3_score") == -1000) {
						String sql = "UPDATE active_games SET host_players_turn=2, away_player_r3_score=" + turnScore + "  WHERE idactive_Games = " + gameId;
						st.executeUpdate(sql);
						response[1] = "p2r3";


						int hostPlayerId = rs.getInt("host_player");
						int awayPlayerId = rs.getInt("away_player");
						int hostPlayerScore = rs.getInt("host_player_r1_score") + rs.getInt("host_player_r2_score") + rs.getInt("host_player_r3_score");
						int awayPlayerScore = rs.getInt("away_player_r1_score") + rs.getInt("away_player_r2_score") + turnScore;
						if(hostPlayerScore > awayPlayerScore) {
							String sql1 = "UPDATE users SET wins=wins + 1 WHERE user_id=" + hostPlayerId;
							st2.executeUpdate(sql1);
							String sql2 = "UPDATE users SET loses=loses + 1 WHERE user_id=" + awayPlayerId;
							st3.executeUpdate(sql2);
						}
						else if(awayPlayerScore > hostPlayerScore) {
							String sql1 = "UPDATE users SET wins=wins + 1 WHERE user_id=" + awayPlayerId;
							st2.executeUpdate(sql1);
							String sql2 = "UPDATE users SET loses=loses + 1 WHERE user_id=" + hostPlayerId;
							st3.executeUpdate(sql2);
						}
						else {
							String sql1 = "UPDATE users SET tie=tie + 1 WHERE user_id=" + awayPlayerId + " OR user_id=" + hostPlayerId;
							st2.executeUpdate(sql1);
						}
					}
					else{
						System.out.println("An error has occured: All turns are over");
						response[0] = "ERROR";
					}
				}
				else{
					response[0] = "ERROR";
				}
				con.close();
				st.close();
				st1.close();
				rs.close();
			}
			else if(message[0].equals("profile_screen")){
				response = new String[5];
				String userId = message[1];
				Class.forName("com.mysql.jdbc.Driver");
		        Connection con = DriverManager.getConnection("jdbc:mysql://localhost/BDD?user=root");
				Statement st = con.createStatement();
				ResultSet rs;
				
				response[0] = "success_profile_screen";
				rs = st.executeQuery("SELECT * FROM users u WHERE u.name = '" + userId +"'");
				if(rs.next()){
					String name = rs.getString("name");
					int wins = rs.getInt("wins");
					int losses = rs.getInt("loses");
					int ties = rs.getInt("ties");
						
					response[1] = name;
					response[2] = Integer.toString(wins);
					response[3] = Integer.toString(losses);
					response[4] = Integer.toString(ties);
				}
				else{
					response = new String[1];
					response[0] = "ERROR";
				}
			}
			else{
				response[0] = "bad_cmd";
				System.err.println("BadCommand");
			}

			System.out.println(response[0]);
			ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
			oos.writeObject(response);

		} 
		catch(Exception ex){
			ex.printStackTrace();
			System.err.println(ex.toString());
		}		
	}

	
	public static void addGameData(String[] response, ResultSet hostPlayer, ResultSet awayPlayer) throws Exception{
		for(int i = 1; i < response.length - 1; i+=ELEMENTS_PER_GAME_PACKAGE) {
			System.out.println("ALEN: " + getRowCount(awayPlayer));
			System.out.println("HLEN: " + getRowCount(hostPlayer));
			if(hostPlayer.next()){
				response[i] = Integer.toString(hostPlayer.getInt("idActive_Games"));
				response[i + 1] = hostPlayer.getString("name");
				System.out.println(hostPlayer.getString("name"));
				System.out.println(hostPlayer.getInt("user_id"));
				
				int awayPlayerId = hostPlayer.getInt("user_id");
				int needsOk = hostPlayer.getInt("need_game_ok");
				
				if(awayPlayerId == needsOk || needsOk < 0) {
					response[i + 3] = "0";
				}
				else {
					response[i + 3] = "1";
				}
						
				
				if(hostPlayer.getInt("host_players_turn") == 1){
					response[i + 2] = "your_turn";
				}
				else if(hostPlayer.getInt("host_players_turn") == 0){
					response[i + 2] = "their_turn";
				}
				else {
					response[i + 2] = "game_over";
				}
			}
			else if(awayPlayer.next()){
				response[i] = Integer.toString(awayPlayer.getInt("idActive_Games"));
				response[i + 1] = awayPlayer.getString("name");
				
				int awayPlayerId = awayPlayer.getInt("user_id");
				int needsOk = awayPlayer.getInt("need_game_ok");
				
				if(awayPlayerId == needsOk || needsOk < 0) {
					response[i + 3] = "0";
				}
				else {
					response[i + 3] = "1";
				}
				
				if(awayPlayer.getInt("host_players_turn") == 1){
					response[i + 2] = "their_turn";
				}
				else if(awayPlayer.getInt("host_players_turn") == 0){
					response[i + 2] = "your_turn";
				}
				else {
					response[i + 2] = "game_over";
				}
			}
			else{
				response[0] = "error";
				System.err.println("Something went horribly wrong...");
				break;
			}
		}

	}

	public static int getRowCount(ResultSet set) throws SQLException  
	{
		int rowCount;  
		int currentRow = set.getRow();            // Get current row  
		rowCount = set.last() ? set.getRow() : 0; // Determine number of rows  
		if (currentRow == 0)                      // If there was no current row  
			set.beforeFirst();                     // We want next() to go to first row  
		else                                      // If there WAS a current row  
			set.absolute(currentRow);              // Restore it  
		return rowCount;
	}

	public static String createRandomBoard(){
		char[] theBoard = new char[BOARD_HEIGHT*BOARD_WIDTH];

		Random generator = new Random(System.currentTimeMillis());
		ArrayList<Integer> checker = new ArrayList<Integer>();

		for(int i = 0; i < numMines; i++){
			int bombSpot = 0;
			do{
				bombSpot = generator.nextInt(theBoard.length);
			}while(checker.contains(bombSpot));

			theBoard[bombSpot] = BOMB_SPACE;
			checker.add(bombSpot);

		}
		calculateNumbers(theBoard);

		return new String(theBoard);
	}

	public static String createBlankBoard(){
		String theBoard = "";

		for(int i = 0; i < BOARD_HEIGHT * BOARD_WIDTH; i++){
			theBoard += "C";
		}

		return theBoard;
	}

	public static void calculateNumbers(char[] theBoard){
		for(int i = 0; i < BOARD_HEIGHT; i++){
			for(int j = 0; j < BOARD_WIDTH; j++){
				if(theBoard[i * BOARD_WIDTH + j] == BOMB_SPACE)
					continue;
				int numBombs = 0;
				for(int k = -1; k <= 1; k++){
					for(int l = -1; l <= 1; l++){
						if(i + k < BOARD_HEIGHT && i + k >= 0 && j + l >= 0 && j + l < BOARD_WIDTH){
							if(theBoard[(i+k) * BOARD_WIDTH + j + l] == BOMB_SPACE)
								numBombs++;
						}						
					}
				}
				theBoard[i * BOARD_WIDTH + j] = (char)(numBombs + '0');
			}
		}
	}

}
